/**
 * @
 * @FilePath     : result.h
 * @Version      : 1.0
 * @Description  : Result模式实现 - 统一的错误处理和返回值封装
 * @
 * @Author       : 岳凯(1585202329@qq.com)
 * @Date         : 2025-01-23 00:00:00
 * @
 * @LastEditors  : 岳凯(1585202329@qq.com)
 * @LastEditTime : 2025-08-28 22:01:00
 */
#pragma once

#include <QDebug>
#include <QString>
#include <optional>
#include <stdexcept>

namespace kernel {

/**
 * @enum ErrorCode
 * @brief 错误代码枚举 - 定义系统中所有可能的错误类型
 */
enum class ErrorCode {
  // 成功状态
  Success = 0,

  // 通用错误 (1000-1999)
  UnknownError = 1000,
  InvalidInput = 1001,
  InvalidOperation = 1002,
  InvalidState = 1003,
  NotImplemented = 1004,
  InvalidArgument = 1005,
  BusinessError,
  // 数据相关错误 (2000-2999)
  EntityNotFound = 2000,
  DuplicateKey = 2001,
  DataValidationFailed = 2002,
  DataCorrupted = 2003,
  DataTooLarge = 2004,
  AlreadyExists = 2005,
  ProtocolError,

  // 数据库相关错误 (3000-3999)
  DatakernelConnectionError = 3000,
  DatakernelNotInitialized = 3001,
  DatakernelQueryFailed = 3002,
  DatakernelTransactionFailed = 3003,
  DatakernelConstraintViolation = 3004,
  DatakernelTimeout = 3005,
  SqlPreparationError,
  SqlExecutionError,

  // 认证和授权错误 (4000-4999)
  AuthenticationFailed = 4000,
  AuthorizationFailed = 4001,
  UserAccountLocked = 4002,
  UserAccountExpired = 4003,
  InvalidCredentials = 4004,
  SessionExpired = 4005,

  // 业务逻辑错误 (5000-5999)
  BusinessRuleViolation = 5000,
  InsufficientPermissions = 5001,
  ResourceNotAvailable = 5002,
  OperationNotAllowed = 5003,
  ConcurrencyConflict = 5004,
  TransactionCommitFailed,
  TransactionStartFailed,
  DeviceNotFound,
  InvalidConfiguration,
  NotFound,
  DeviceCreationFailed,
  DeviceNotReady,
  DeviceTypeNotSupported,
  DeviceTypeAlreadyRegistered,
  ValidationError,
  DeviceNotConnected,
  DeviceConnectionFailed,
  DeviceOperationFailed,
  CommunicationTimeout,
  InvalidResponse,
  DeviceError,
  InvalidParameter,
  BusinessLogicError,
  ServiceInitializationFailed,
  ServiceShutdownFailed,
  DataNotAvailable,
  Timeout,
  ParseError,
  // 系统错误 (6000-6999)
  SystemError = 6000,
  OutOfMemory = 6001,
  FileNotFound = 6002,
  FileAccessDenied = 6003,
  NetworkError = 6004,
  TimeoutError = 6005,
  IOError,
  DeviceTimeout,
  DeviceTransmissionFailed,
  QueueFull,
  FileSystemError,

  // 服务错误 (7000-7999)
  ServiceNotInitialized = 7000,
  ServiceUnavailable = 7001,
  ServiceUnhealthy = 7002,
  InitializationFailed = 7003,
  ConfigurationError = 7004,
  ServiceNotRegistered = 7005,

  // 外部依赖错误 (8000-8999)
  ExternalServiceError = 8000,
  ThirdPartyApiError = 8001,
  IntegrationError = 8002
};

/**
 * @class Result
 * @brief Result模式实现 - 封装操作结果和错误信息
 * @tparam T 成功时返回的值类型
 */
template <typename T>
class Result {
 public:
  /**
   * @brief 默认构造函数 - 创建失败的结果
   */
  Result()
      : m_success(false),
        m_errorCode(ErrorCode::UnknownError),
        m_errorMessage("未知错误") {}

  /**
   * @brief 成功结果构造函数
   * @param value 成功时的返回值
   */
  explicit Result(const T& value)
      : m_success(true), m_value(value), m_errorCode(ErrorCode::Success) {}

  /**
   * @brief 成功结果构造函数（移动语义）
   * @param value 成功时的返回值
   */
  explicit Result(T&& value)
      : m_success(true),
        m_value(std::move(value)),
        m_errorCode(ErrorCode::Success) {}

  /**
   * @brief 失败结果构造函数
   * @param errorCode 错误代码
   * @param errorMessage 错误消息
   */
  Result(ErrorCode errorCode, const QString& errorMessage)
      : m_success(false),
        m_errorCode(errorCode),
        m_errorMessage(errorMessage) {}

  /**
   * @brief 拷贝构造函数
   */
  Result(const Result& other) = default;

  /**
   * @brief 移动构造函数
   */
  Result(Result&& other) noexcept = default;

  /**
   * @brief 拷贝赋值操作符
   */
  Result& operator=(const Result& other) = default;

  /**
   * @brief 移动赋值操作符
   */
  Result& operator=(Result&& other) noexcept = default;

  /**
   * @brief 析构函数
   */
  ~Result() = default;

  // ================== 静态工厂方法 ==================

  /**
   * @brief 创建成功的结果
   * @param value 成功时的返回值
   * @return Result<T> 成功的结果对象
   */
  static Result<T> success(const T& value) { return Result<T>(value); }

  /**
   * @brief 创建成功的结果（移动语义）
   * @param value 成功时的返回值
   * @return Result<T> 成功的结果对象
   */
  static Result<T> success(T&& value) { return Result<T>(std::move(value)); }

  /**
   * @brief 创建失败的结果
   * @param errorCode 错误代码
   * @param errorMessage 错误消息
   * @return Result<T> 失败的结果对象
   */
  static Result<T> failure(ErrorCode errorCode, const QString& errorMessage) {
    return Result<T>(errorCode, errorMessage);
  }

  /**
   * @brief 创建失败的结果（仅错误代码）
   * @param errorCode 错误代码
   * @return Result<T> 失败的结果对象
   */
  static Result<T> failure(ErrorCode errorCode) {
    return Result<T>(errorCode, errorCodeToString(errorCode));
  }

  // ================== 状态检查方法 ==================

  /**
   * @brief 检查操作是否成功
   * @return bool 是否成功
   */
  bool isSuccess() const { return m_success; }

  /**
   * @brief 检查操作是否失败
   * @return bool 是否失败
   */
  bool isFailure() const { return !m_success; }

  /**
   * @brief 布尔转换操作符
   * @return bool 是否成功
   */
  explicit operator bool() const { return m_success; }

  // ================== 值访问方法 ==================

  /**
   * @brief 获取成功时的值
   * @return const T& 值的引用
   * @throws std::runtime_error 如果结果是失败的
   */
  const T& getValue() const {
    if (!m_success) {
      throw std::runtime_error(QString("尝试从失败的Result中获取值: %1")
                                   .arg(m_errorMessage)
                                   .toStdString());
    }
    if (!m_value.has_value()) {
      throw std::runtime_error("Result标记为成功但不包含值 - 内部状态不一致");
    }
    return m_value.value();
  }

  /**
   * @brief 获取成功时的值（移动语义）
   * @return T 值
   * @throws std::runtime_error 如果结果是失败的
   */
  T takeValue() {
    if (!m_success) {
      throw std::runtime_error(QString("尝试从失败的Result中获取值: %1")
                                   .arg(m_errorMessage)
                                   .toStdString());
    }
    if (!m_value.has_value()) {
      throw std::runtime_error("Result标记为成功但不包含值 - 内部状态不一致");
    }
    return std::move(m_value.value());
  }

  /**
   * @brief 获取值或默认值
   * @param defaultValue 默认值
   * @return T 成功时返回实际值，失败时返回默认值
   */
  T getValueOr(const T& defaultValue) const {
    return m_success ? m_value.value() : defaultValue;
  }

  /**
   * @brief 检查是否有值
   * @return bool 是否有值
   */
  bool hasValue() const {
    // 只有成功且确实包含值时才返回true
    return m_success && m_value.has_value();
  }

  /**
   * @brief 验证内部状态一致性
   * @return bool 状态是否一致
   */
  bool isStateConsistent() const {
    if (m_success) {
      // 成功状态必须有值
      return m_value.has_value();
    } else {
      // 失败状态不应该有值，但这不是强制要求
      return true;
    }
  }

  // ================== 错误信息访问方法 ==================

  /**
   * @brief 获取错误代码
   * @return ErrorCode 错误代码
   */
  ErrorCode getErrorCode() const { return m_errorCode; }

  /**
   * @brief 获取错误消息
   * @return QString 错误消息
   */
  QString getErrorMessage() const { return m_errorMessage; }

  /**
   * @brief 获取详细的错误信息
   * @return QString 包含错误代码和消息的详细信息
   */
  QString getDetailedError() const {
    return QString("错误代码: %1, 错误消息: %2")
        .arg(static_cast<int>(m_errorCode))
        .arg(m_errorMessage);
  }

  // ================== 函数式编程支持 ==================

  /**
   * @brief 映射操作 - 如果成功则应用函数转换值
   * @tparam U 转换后的类型
   * @param func 转换函数
   * @return Result<U> 转换后的结果
   */
  template <typename U>
  Result<U> map(std::function<U(const T&)> func) const {
    if (m_success) {
      try {
        return Result<U>::success(func(m_value.value()));
      } catch (const std::exception& e) {
        return Result<U>::failure(ErrorCode::SystemError,
                                  QString("映射操作异常: %1").arg(e.what()));
      }
    } else {
      return Result<U>::failure(m_errorCode, m_errorMessage);
    }
  }

  /**
   * @brief 平铺映射操作 - 如果成功则应用返回Result的函数
   * @tparam U 转换后的类型
   * @param func 转换函数
   * @return Result<U> 转换后的结果
   */
  template <typename U>
  Result<U> flatMap(std::function<Result<U>(const T&)> func) const {
    if (m_success) {
      try {
        return func(m_value.value());
      } catch (const std::exception& e) {
        return Result<U>::failure(
            ErrorCode::SystemError,
            QString("平铺映射操作异常: %1").arg(e.what()));
      }
    } else {
      return Result<U>::failure(m_errorCode, m_errorMessage);
    }
  }

  /**
   * @brief 过滤操作 - 如果成功且满足条件则保持成功
   * @param predicate 过滤条件
   * @param errorMessage 不满足条件时的错误消息
   * @return Result<T> 过滤后的结果
   */
  Result<T> filter(std::function<bool(const T&)> predicate,
                   const QString& errorMessage = "过滤条件不满足") const {
    if (m_success) {
      try {
        if (predicate(m_value.value())) {
          return *this;
        } else {
          return Result<T>::failure(ErrorCode::DataValidationFailed,
                                    errorMessage);
        }
      } catch (const std::exception& e) {
        return Result<T>::failure(ErrorCode::SystemError,
                                  QString("过滤操作异常: %1").arg(e.what()));
      }
    } else {
      return *this;
    }
  }

  // ================== 工具方法 ==================

  /**
   * @brief 错误代码转字符串
   * @param errorCode 错误代码
   * @return QString 错误代码对应的字符串描述
   */
  static QString errorCodeToString(ErrorCode errorCode) {
    switch (errorCode) {
      case ErrorCode::Success:
        return "成功";
      case ErrorCode::UnknownError:
        return "未知错误";
      case ErrorCode::InvalidInput:
        return "输入无效";
      case ErrorCode::InvalidOperation:
        return "操作无效";
      case ErrorCode::InvalidState:
        return "状态无效";
      case ErrorCode::NotImplemented:
        return "功能未实现";
      case ErrorCode::InvalidArgument:
        return "参数无效";
      case ErrorCode::EntityNotFound:
        return "实体未找到";
      case ErrorCode::DuplicateKey:
        return "重复键";
      case ErrorCode::DataValidationFailed:
        return "数据验证失败";
      case ErrorCode::DataCorrupted:
        return "数据损坏";
      case ErrorCode::DataTooLarge:
        return "数据过大";
      case ErrorCode::AlreadyExists:
        return "已存在";
      case ErrorCode::DatakernelConnectionError:
        return "数据库连接错误";
      case ErrorCode::DatakernelNotInitialized:
        return "数据库未初始化";
      case ErrorCode::DatakernelQueryFailed:
        return "数据库查询失败";
      case ErrorCode::DatakernelTransactionFailed:
        return "数据库事务失败";
      case ErrorCode::DatakernelConstraintViolation:
        return "数据库约束违反";
      case ErrorCode::DatakernelTimeout:
        return "数据库超时";
      case ErrorCode::AuthenticationFailed:
        return "认证失败";
      case ErrorCode::AuthorizationFailed:
        return "授权失败";
      case ErrorCode::UserAccountLocked:
        return "用户账户锁定";
      case ErrorCode::UserAccountExpired:
        return "用户账户过期";
      case ErrorCode::InvalidCredentials:
        return "凭据无效";
      case ErrorCode::SessionExpired:
        return "会话过期";
      case ErrorCode::BusinessRuleViolation:
        return "业务规则违反";
      case ErrorCode::InsufficientPermissions:
        return "权限不足";
      case ErrorCode::ResourceNotAvailable:
        return "资源不可用";
      case ErrorCode::OperationNotAllowed:
        return "操作不允许";
      case ErrorCode::ConcurrencyConflict:
        return "并发冲突";
      case ErrorCode::SystemError:
        return "系统错误";
      case ErrorCode::OutOfMemory:
        return "内存不足";
      case ErrorCode::FileNotFound:
        return "文件未找到";
      case ErrorCode::FileAccessDenied:
        return "文件访问被拒绝";
      case ErrorCode::NetworkError:
        return "网络错误";
      case ErrorCode::TimeoutError:
        return "超时错误";
      case ErrorCode::ServiceNotInitialized:
        return "服务未初始化";
      case ErrorCode::ServiceUnavailable:
        return "服务不可用";
      case ErrorCode::ServiceUnhealthy:
        return "服务不健康";
      case ErrorCode::InitializationFailed:
        return "初始化失败";
      case ErrorCode::ConfigurationError:
        return "配置错误";
      case ErrorCode::ServiceNotRegistered:
        return "服务未注册";
      case ErrorCode::SqlPreparationError:
        return "SQL准备错误";
      case ErrorCode::SqlExecutionError:
        return "SQL执行错误";
      case ErrorCode::TransactionCommitFailed:
        return "事务提交失败";
      case ErrorCode::TransactionStartFailed:
        return "事务启动失败";
      case ErrorCode::DeviceNotFound:
        return "设备未找到";
      case ErrorCode::InvalidConfiguration:
        return "无效配置";
      case ErrorCode::NotFound:
        return "未找到";
      case ErrorCode::DeviceCreationFailed:
        return "设备创建失败";
      case ErrorCode::DeviceNotReady:
        return "设备未就绪";
      case ErrorCode::DeviceTypeNotSupported:
        return "不支持的设备类型";
      case ErrorCode::DeviceTypeAlreadyRegistered:
        return "设备类型已注册";
      case ErrorCode::ExternalServiceError:
        return "外部服务错误";
      case ErrorCode::ThirdPartyApiError:
        return "第三方API错误";
      case ErrorCode::IntegrationError:
        return "集成错误";
      default:
        return QString("未知错误代码: %1").arg(static_cast<int>(errorCode));
    }
  }

 private:
  bool m_success;            ///< 操作是否成功
  std::optional<T> m_value;  ///< 成功时的值
  ErrorCode m_errorCode;     ///< 错误代码
  QString m_errorMessage;    ///< 错误消息
};

// ================== 特化版本 ==================

/**
 * @brief Result<void>的特化版本 - 用于不返回值的操作
 */
template <>
class Result<void> {
 public:
  /**
   * @brief 默认构造函数 - 创建失败的结果
   */
  Result()
      : m_success(false),
        m_errorCode(ErrorCode::UnknownError),
        m_errorMessage("未知错误") {}

  /**
   * @brief 成功结果构造函数
   */
  explicit Result(bool success)
      : m_success(success), m_errorCode(ErrorCode::Success) {}

  /**
   * @brief 失败结果构造函数
   * @param errorCode 错误代码
   * @param errorMessage 错误消息
   */
  Result(ErrorCode errorCode, const QString& errorMessage)
      : m_success(false),
        m_errorCode(errorCode),
        m_errorMessage(errorMessage) {}

  // 静态工厂方法
  static Result<void> success() { return Result<void>(true); }
  static Result<void> failure(ErrorCode errorCode,
                              const QString& errorMessage) {
    return Result<void>(errorCode, errorMessage);
  }
  static Result<void> failure(ErrorCode errorCode) {
    return Result<void>(errorCode, Result<int>::errorCodeToString(errorCode));
  }

  // 状态检查
  bool isSuccess() const { return m_success; }
  bool isFailure() const { return !m_success; }
  explicit operator bool() const { return m_success; }

  // 错误信息访问
  ErrorCode getErrorCode() const { return m_errorCode; }
  QString getErrorMessage() const { return m_errorMessage; }
  QString getDetailedError() const {
    return QString("错误代码: %1, 错误消息: %2")
        .arg(static_cast<int>(m_errorCode))
        .arg(m_errorMessage);
  }

 private:
  bool m_success;
  ErrorCode m_errorCode;
  QString m_errorMessage;
};

// ================== 类型别名 ==================

using VoidResult = Result<void>;
using BoolResult = Result<bool>;
using IntResult = Result<int>;
using StringResult = Result<QString>;

// ================== 调试支持 ==================

/**
 * @brief QDebug输出支持
 */
template <typename T>
QDebug operator<<(QDebug debug, const Result<T>& result) {
  QDebugStateSaver saver(debug);
  debug.nospace();

  if (result.isSuccess()) {
    debug << "Result(Success, value=" << result.getValue() << ")";
  } else {
    debug << "Result(Failure, errorCode="
          << static_cast<int>(result.getErrorCode())
          << ", errorMessage=" << result.getErrorMessage() << ")";
  }

  return debug;
}

/**
 * @brief QDebug输出支持 - void特化版本
 */
template <>
inline QDebug operator<<(QDebug debug, const Result<void>& result) {
  QDebugStateSaver saver(debug);
  debug.nospace();

  if (result.isSuccess()) {
    debug << "Result(Success)";
  } else {
    debug << "Result(Failure, errorCode="
          << static_cast<int>(result.getErrorCode())
          << ", errorMessage=" << result.getErrorMessage() << ")";
  }

  return debug;
}

}  // namespace kernel

// ================== 全局类型别名 ==================

using ErrorCode = kernel::ErrorCode;

template <typename T>
using Result = kernel::Result<T>;
using VoidResult = kernel::VoidResult;
using BoolResult = kernel::BoolResult;
using IntResult = kernel::IntResult;
using StringResult = kernel::StringResult;